package KH;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class readXML {
	public static void main(String args[]) throws Exception {
		
		//dem so thanh phan
		try {
			String filepath = "E:/write.xml";
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(filepath);
			//NodeList list = doc.getElementsByTagName("staff");
			NodeList list= doc.getElementsByTagName("company");
			//System.out.println(list1.getLength());
	 
			System.out.println("Tong so thanh phan =  " + list.getLength());
	 
		}
		catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		}// bat loi tao newDocumentBuilder
		catch (IOException ioe) {
			ioe.printStackTrace();//bat loi parse filepath
		}
		catch (SAXException sae) {
			sae.printStackTrace();
		}
		
	  //doc thanh phan
	try {
		 
		File fXmlFile = new File("E:/read.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
	 
		//
		//doc.getDocumentElement().normalize();
	 
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
	 
		NodeList nList = doc.getElementsByTagName("staff");
	 
		System.out.println("----------------------------");
	 
		for (int temp = 0; temp < nList.getLength(); temp++) {
	 
			Node nNode = nList.item(temp);
	 
			System.out.println("\nElement " +temp+" : "+ nNode.getNodeName());
	 
			if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	 
				Element eElement = (Element) nNode;
	 
				System.out.println("Staff id : " + eElement.getAttribute("id"));
				System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());//lay ten dau tien tim dc
				System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
				System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
				System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
	 
			}
		}
	    } catch (Exception e) {
		e.printStackTrace();
	    }
}
}

